# 2023/2/2  14:38
import pymysql

from config import DBConfig


class DBUtils(object):
    __conn = None


    @classmethod
    def __get_conn(cls):
        """
        为了不让用户随意创建连接造成浪费定义成私有
        :return:
        """
        if cls.__conn is None:
            cls.__conn=pymysql.connect(host=DBConfig.HOST, port=DBConfig.PORT, user=DBConfig.USER,
                                       password=DBConfig.PASSWORD,database=DBConfig.DATABASE, charset=DBConfig.CHARSET)
        return cls.__conn


    @classmethod
    def __close_conn(cls):
        if cls.__conn:
            cls.__conn.close()
            cls.__conn=None



    @classmethod
    def get_one(cls,sql):
        """
        定义获取一条而不是获取所有是因为断言的时候往往是断言一条
        :return:
        """
        result=None
        cursor=None

        try:
            conn=cls.__get_conn()
            cursor=conn.cursor()
            cursor.execute(sql)
            result=cursor.fetchone()
        except Exception as e:
            print(e)
            raise e
        finally:
            if cursor:
                cursor.close()
            cls.__close_conn()
        return result


    @classmethod
    def uid_db(cls,sql):
        conn=None
        cursor=None
        try:
            conn=cls.__get_conn()
            cursor=conn.cursor()
            cursor.execute(sql)
            conn.commit()
        except Exception as e:
            print(e)
            if conn:
                conn.rollback()
            raise e

        finally:
            if cursor:
                cursor.close()
            cls.__close_conn()



if __name__ == '__main__':
    result=DBUtils.get_one("SELECT * FROM employees;")
    print(result)
